const wsMap = {}; // 用于存储WebSocket对象的Map
var ws;

const chatDisplay = document.querySelector('.chat-display');
const messageInput = document.getElementById('message-input');
const submitBtn = document.getElementById('submit-btn');
const messages=[];//改了{}
var customerID;
var username;
// var customerID=document.getElementById("userid").textContent;//加上了
// console.log(customerID);
const msgList=document.querySelector(".msgrows");

$('.msgrows').on('click', function() {
    // 获取点击行在表格中的索引（从0开始计数）
    const rowIndex = $(this).index();
    username = customerID;
    customerID = $(this).find('#userid').text();

    // 输出当前行的 userid
    console.log('User ID:', customerID);

    // 现在您可以使用rowIndex执行任何需要的操作
    console.log('Clicked row index:', rowIndex);
    const Url='ws://localhost:8081/chat/'+customerID;

    // const ws = new WebSocket(Url);
    createWebSocket(Url);

    // ws.onopen = function(event) {
    //   console.log('WebSocket 连接成功');
    // };
    // console.log('customerid='+customerID);
    // ws.onmessage = function(event) {
    //   const message = JSON.parse(event.data);
    //   console.log('onmessage');
    //   // 其他代码保持不变
    //   // // 清空消息列表的内容
    //   // chatDisplay.innerHTML = '';
    //
    //   console.log(event.data)
    //   console.log(message);//可以打印,结果为[{"adminname":"admin","content":"你好","createTime":"2024-03-20T22:08:52","direction":1,"id":1,"username":"1"}]
    //   // 解析消息内容
    //   const content = message[0].content;
    //   console.log(content)//ok,message为数组
    //   const time = new Date(message[0].createTime).toLocaleString();
    //   const userId = message[0].username;
    //   const adminId = message[0].adminname;
    //   const direction = message[0].direction;
    //   messages[userId]=content;
    //   // renderMessageList();
    //   // 构建消息 HTML 元素
    //   const messageItem = document.createElement('li');
    //   messageItem.textContent = `${time} - User ${userId} to Admin ${adminId}: ${content}`;
    //   messageItem.style.color = direction === 1 ? 'blue' : 'green'; // 根据方向设置消息颜色
    //   // 将消息添加到消息列表中
    //   chatDisplay.appendChild(messageItem);
    // };

});

// msgList.addEventListener('click',function () {
//
//   const currentRow = $(this).index();
//   console.log('row='+currentRow);
//   const Url='ws://localhost:8081/chat/'+customerID;
//   // const ws = new WebSocket(Url);
//   createWebSocket(Url);
//   ws.userType="admin";
//   ws.onopen = function(event) {
//     console.log('WebSocket 连接成功');
//   };
//
//   ws.onmessage = function(event) {
//     const message = JSON.parse(event.data);
//     console.log('onmessage');
//
//     // 其他代码保持不变
//
//     // 清空消息列表的内容
//     chatDisplay.innerHTML = '';
//
//     console.log(event.data)
//     console.log(message);//可以打印,结果为[{"adminname":"admin","content":"你好","createTime":"2024-03-20T22:08:52","direction":1,"id":1,"username":"1"}]
//     // 解析消息内容
//     const content = message[0].content;
//     console.log(content)//ok,message为数组
//     const time = new Date(message[0].createTime).toLocaleString();
//     const userId = message[0].username;
//     const adminId = message[0].adminname;
//     const direction = message[0].direction;
//     messages[userId]=content;
//     // renderMessageList();
//     // 构建消息 HTML 元素
//     const messageItem = document.createElement('li');
//     messageItem.textContent = `${time} - User ${userId} to Admin ${adminId}: ${content}`;
//     messageItem.style.color = direction === 1 ? 'blue' : 'green'; // 根据方向设置消息颜色
//     // 将消息添加到消息列表中
//     chatDisplay.appendChild(messageItem);
//   };
//
// })

//更新数据
function renderMessageList(){
    msgList.innerHTML="";
    for (const userId in messages) {
        const messageItem = document.createElement('div');
        messageItem.textContent = `User ${userId}: ${messages[userId]}`;
        messageItem.classList.add('msgList');
        messageItem.dataset.userId = userId;
        messages.push(messageItem); // 将消息元素添加到数组中
    }
    messages.forEach(element=>{
        msgList.appendChild(element);
    })
}

window.addEventListener('beforeunload', function() {//离开页面时关闭Websocket连接
    ws.close();
});

function createWebSocket(url) {
    if(ws!=null){
        ws.close();
    }

    // if (!wsMap[url]) {
    ws = new WebSocket(url);
    wsMap[url] = ws;
    ws.userType="admin";
    // 设置WebSocket事件处理
    ws.onopen = function(event) {
        console.log('WebSocket 连接成功');
    };
    ws.onclose=function (event) {
        console.log('close');

        var url = `/admin/closeChat?customerId=` + username;

        console.log("关闭的是"+ username);
        fetch(url,{
            method:'GET'
        }) .then(response => response.json())
            .catch(error => {
                console.error('请求发送失败:', error);
            });
    }

    ws.onmessage = function(event) {
        chatDisplay.innerHTML = '';
        // 处理接收到的消息
        const msg = JSON.parse(event.data);
        console.log('onmessage');
        // 其他代码保持不变
        // // 清空消息列表的内容
        // chatDisplay.innerHTML = '';

        console.log(event.data)
        console.log(msg);//可以打印,结果为[{"adminname":"admin","content":"你好","createTime":"2024-03-20T22:08:52","direction":1,"id":1,"username":"1"}]
        // 解析消息内容
        //
        // messages[userId]=content;
        // renderMessageList();
        // 构建消息 HTML 元素

        msg.forEach(function (message) {
            const content = message.content;
            console.log(content)//ok,message为数组
            const time = new Date(message.createTime).toLocaleString();
            const userId = message.username;
            const adminId = message.adminname;
            const direction = message.direction;
            const messageItem = document.createElement('li');
            messageItem.textContent = `${time} - User ${userId} to Admin ${adminId}: ${content}`;
            messageItem.style.color = direction === 1 ? 'blue' : 'green'; // 根据方向设置消息颜色
            messageItem.style.display = 'block'; // 设置每个 li 元素独占一行
            messageItem.style.backgroundColor='white';
            // 将消息添加到消息列表中
            console.log(messageItem);
            chatDisplay.appendChild(messageItem);
        })


    };

    // 其他事件处理逻辑

    // }
}

function sendMsg(){
    var time = Date.now();
    var date = new Date(time);
    // var formattedDate = date.toISOString().slice(0, 19).replace('T', ' ');

    var year = date.getFullYear();
    var month = String(date.getMonth() + 1).padStart(2, '0');
    var day = String(date.getDate()).padStart(2, '0');
    var hours = String(date.getHours()).padStart(2, '0');
    var minutes = String(date.getMinutes()).padStart(2, '0');
    var seconds = String(date.getSeconds()).padStart(2, '0');

// 构造日期时间字符串
    var formattedDate = year + '-' + month + '-' + day + 'T' + hours + ':' + minutes + ':' + seconds;
    console.log(formattedDate)
    var adminid = /*[[${session.loginAdmin.adminname}]]*/ null;
    console.log('adminid='+adminid);
    console.log("?");//按钮触发失败
    const message = messageInput.value;
    let sendObject=JSON.stringify({
        content:message,
        createTime:formattedDate,
        username:customerID,
        adminname:adminid,
        direction:0 });
    console.log(sendObject);
    ws.send(sendObject);
    // const messageItem = document.createElement('li');
    // messageItem.textContent = message;
    // messageItem.style.color ='green'; // 根据方向设置消息颜色
    // // 将消息添加到消息列表中
    // document.getElementById('message-list').appendChild(messageItem);
    messageInput.value = ''; // 清空输入框
}

// submitBtn.addEventListener('click', function() {
//
// });